import { ref } from "vue";
import { defineStore } from "pinia";
import { loginAPI } from "@/apis/user";
import { mergeCartAPI } from "@/apis/cart";
import type { User } from "@/apis/user";
import type { LoginUser } from "@/types/login/login";
import { useCartStore } from "./cartStore";
export const useUserStore = defineStore(
  "counter",
  () => {
    const cartStore = useCartStore();
    const userInfo = ref<User>({} as User);
    const getUserInfo = async ({ account, password }: LoginUser) => {
      const res = await loginAPI({ account, password } as LoginUser);
      userInfo.value = res.data.result;
      mergeCartAPI(
        cartStore.cartList.map((item: any) => {
          return {
            skuId: item.skuId,
            count: item.count,
            selected: item.selected,
          };
        })
      );
      cartStore.updateNewList()
    };
    const logout = () => {
      userInfo.value = {} as User;
      cartStore.clearCart();
    };
    return {
      userInfo,
      getUserInfo,
      logout,
    };
  },
  {
    persist: true, // 开启数据持久化
  }
);
